﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using WeifenLuo.WinFormsUI.Docking;
using WHC.Security.Entity;
using System.Collections;
using System.Xml;
using System.IO;
using Cls_Business;


//xml
namespace CKNetFrameWork
{
    public partial class Frm_Main : Form
    {

        private Frm_MainToolWindow mainToolWin = null;
        private static Frm_Main m_Frm_Main = null;
        public static int m_nDfuColWidth = 70;
        public static Dictionary<string, Dictionary<string, string>> m_dicFormText2FormTypeName = new Dictionary<string, Dictionary<string, string>>();
        private List<FunctionInfo> m_lstOneLevelFunRuntime = new List<FunctionInfo>();
        private WHC.Security.BLL.Function function = new WHC.Security.BLL.Function();
        GlobalControl gc = null;
  

        public void OnShowWindow(object sender, MyEventArgs e)          //事件处理函数，其签名应与代理签名相同
        {
            ShowContent(e._strName);
        }

        public Frm_Main()
        {
            InitializeComponent();
            InitFormText2FormType();
    
            InitFirstLevelFun();
            InitSecondLevelFun();
            
        }

        private void InitMenuItem()
        {
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Name = strModule; //menuname
                item.Text = strModule;
                //menuStrip1.Items[item.Name].Enabled = true;
                InitSubMenuItem(item);
                menuStrip1.Items.Add(item);
            }

        }
        private void InitSubMenuItem(ToolStripItem item)
        {
            string mname = item.Name;
            ToolStripMenuItem pItem = (ToolStripMenuItem)item;
            //根据父菜单项加载子菜单
            foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[mname].Keys)
            {
                try
                {
                    ToolStripMenuItem subItem = new ToolStripMenuItem();
                    subItem.Name = strItem; //menuname
                    subItem.Text = strItem;
                    subItem.Click += new EventHandler(subItem_Click);
                    pItem.DropDownItems.Add(subItem);
                    //pItem.DropDownItems[strItem].Enabled = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }

        }
        void subItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            ShowContent(tsmi.Text.ToString());
            return;
        }

        //将xml文件转换为DataSet
        public static DataSet ConvertXMLFileToDataSet(string xmlFile)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                XmlDocument xmld = new XmlDocument();
                xmld.Load(xmlFile);

                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmld.InnerXml);
                //从stream装载到XmlTextReader
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                //xmlDS.ReadXml(xmlFile);
                return xmlDS;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }
        private void InitFormText2FormType()
        {
            string orgCodePath = Application.StartupPath + "\\func.xml";
            DataSet ds = ConvertXMLFileToDataSet(orgCodePath);
            DataTable dt = ds.Tables[0];
            DataRow[] rows = dt.Select("ParentID='-1'");

            
            foreach (DataRow row in rows)
            {
                string strID = row["ID"].ToString();
                string strModuleName = row["Name"].ToString();

                Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
                DataRow[] childRows = dt.Select("ParentID='" + strID.ToString() + "'");
                foreach (DataRow rowChild in childRows)
                {
                    string strName = rowChild["Name"].ToString();
                    string strNameSpace = rowChild["Namespace"].ToString();
                    dicCSharpBase.Add(strName, strNameSpace);
                }
                m_dicFormText2FormTypeName.Add(strModuleName, dicCSharpBase);
            }
            return;
         
        }
        //初始化一次每次新增模块时调用
        private void InitFirstLevelFun()
        {
 
            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFirstLevelFunctions();
            List<string> listName = new List<string>();
            foreach(FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }
            foreach (string strTemp in m_dicFormText2FormTypeName.Keys)
            {
                if (listName.Contains(strTemp))
                    continue;
                FunctionInfo info = new FunctionInfo();
                info.Name = strTemp;
                info.PID = -1;
                info.ControlID = "";
                info.SystemType_ID = "WareMis";
                function.Insert(info);
            }
        }
        //初始化一次每次新增模块时调用
        private void InitSecondLevelFun()
        {


            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFunctions();
            List<string> listName = new List<string>();
            foreach (FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }

            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                FunctionInfo fi = function.FindSingle("name='" + strModule+"'");
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (listName.Contains(strItem))
                        continue;
                    FunctionInfo info = new FunctionInfo();
                    info.Name = strItem;
                    info.PID = fi.ID;
                    info.ControlID = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                    info.SystemType_ID = "WareMis";
                    int nID = function.Insert2(info);

                    FunctionInfo infoAdd = new FunctionInfo();
                    infoAdd.Name = strItem + "_增加";
                    infoAdd.PID = nID;
                    infoAdd.ControlID = "";
                    infoAdd.SystemType_ID = "WareMis";
                    function.Insert(infoAdd);

                    FunctionInfo infoMod = new FunctionInfo();
                    infoMod.Name = strItem + "_修改";
                    infoMod.PID = nID;
                    infoMod.ControlID = "";
                    infoMod.SystemType_ID = "WareMis";
                    function.Insert(infoMod);

                    FunctionInfo infoDel = new FunctionInfo();
                    infoDel.Name = strItem + "_删除";
                    infoDel.PID = nID;
                    infoDel.ControlID = "";
                    infoDel.SystemType_ID = "WareMis";
                    function.Insert(infoDel);
                }
            }
        }
        private string GetParentName(FunctionInfo functionInfoChild)
        {
            foreach (FunctionInfo functionInfo in m_lstOneLevelFunRuntime)
            {
                if (functionInfo.ID == functionInfoChild.PID)
                {
                    return functionInfo.Name;
                }
            }
            return "";
        }
        private void InitFormText2FormTypeNameDic()
        {
            m_lstOneLevelFunRuntime.Clear();
            m_dicFormText2FormTypeName.Clear();
            List<FunctionInfo> UserFunList = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetFunctionsByUser(GlobalControl.m_nLoginUserId, "WareMis");

            if (UserFunList != null && UserFunList.Count > 0)
            {

                foreach (FunctionInfo functionInfo in UserFunList)
                {
                    if (functionInfo.PID == -1)
                    {
                        Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
                        m_dicFormText2FormTypeName.Add(functionInfo.Name, dicCSharpBase);
                        m_lstOneLevelFunRuntime.Add(functionInfo);
                    }
                }

                foreach (FunctionInfo functionInfoFather in m_lstOneLevelFunRuntime)
                {
                    foreach (FunctionInfo functionInfo in UserFunList)
                    {
                        if (functionInfo.PID == functionInfoFather.ID)
                        {
                            
                            //string strTemp = GetParentName(functionInfo);
                            if (m_dicFormText2FormTypeName.Keys.Contains(functionInfoFather.Name))
                                m_dicFormText2FormTypeName[functionInfoFather.Name].Add(functionInfo.Name, functionInfo.ControlID);
                               

                        }
                    }
                }

            }

            return;
           
            
        }
        public static Frm_Main GetMainForm()
        {
            if (m_Frm_Main == null)
            {
                m_Frm_Main = new Frm_Main();
            }

            return m_Frm_Main;
        }

        private DockContent FindDocument(string text)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.DockingMdi)
            {
                foreach (Form form in MdiChildren)
                {
                    if (form.Text == text)
                    {
                        return form as DockContent;
                    }
                }

                return null;
            }
            else
            {
                foreach (DockContent content in dockPanel.Documents)
                {
                    if (content.DockHandler.TabText == text)
                    {
                        return content;
                    }
                }

                return null;
            }
        }

        public void ShowContent(DockContent frm)
        {
            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
        }

        private string GetClassByName(string strName)
        {
            string strTemp = "";
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (strItem == strName)
                    {
                        strTemp = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                        break;
                    }
                }
            }
     
            return strTemp;
        }

        private bool HaveFun(string strTemp)
        {
            bool bRet = false;
      

            foreach (string strModule in m_dicFormText2FormTypeName.Keys)
            {
            
                if (m_dicFormText2FormTypeName[strModule].Keys.Contains(strTemp))
                {
                    bRet = true;
                    break;
                }
              
            }
            return bRet;
        }

        private Object ShowContentEx(string strTemp)
        {
            string[] strSplit = strTemp.Split('.');
            string strAssemblyName = strSplit[0];

            Assembly assembly = Assembly.Load(strAssemblyName);
            //test(assembly);

            Type typForm = assembly.GetType(strTemp);
            //关于InvokeMember用法，不明白的可以查看：http://msdn.microsoft.com/zh-cn/library/de3dhzwy(VS.80).aspx
            Object mdiChild = typForm.InvokeMember(
               null,
                BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
               null,
               null,
               null);

            return mdiChild;
        }
     
        public DockContent ShowContent(string caption/*, Type formType*/)
        {

            DockContent frm = FindDocument(caption);

            if (frm == null)
            {
                if (!HaveFun(caption))
                    return null;
                string strTemp = GetClassByName(caption);
                if (strTemp == "")
                    return null;


                Object mdiChild = ShowContentEx(strTemp);

                if (mdiChild != null)
                {
                    frm = mdiChild as DockContent;
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;

                }
            }

            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
            return frm;
        }

        private void Frm_Main_Load(object sender, EventArgs e)
        {
            try
            {

                Frm_Login frm_login = new Frm_Login();

                if (frm_login.ShowDialog() == DialogResult.OK)
                {
                    int a = 0;
                }
                else
                {
                    int b = 0;
                    Application.Exit();
                    return;
                }

                gc = GlobalControl.GetGlobalControl();
                gc.OnShowWindow += new ShowWindow(OnShowWindow);
                InitFormText2FormTypeNameDic();//获取权限
                if (Frm_Main.m_dicFormText2FormTypeName.Count != 0)
                {
                    mainToolWin = new Frm_MainToolWindow();
                    mainToolWin.Show(this.dockPanel, DockState.DockLeft);
                    InitMenuItem();
                  
                }

                this.dockPanel.DockLeftPortion = 0.17;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return ;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            WHC.Security.UI.Portal.StartLogin();
        }

        private void toolStripButtonCloseAll_Click(object sender, EventArgs e)
        {
            foreach (Form mdiChildFrm in this.MdiChildren)
            {
                mdiChildFrm.Close();
            }
        }

        private void toolStripButtonHelp_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Environment.Exit(1);//退出程序
        }

        private void toolStripButtonAbout_Click(object sender, EventArgs e)
        {
       
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Close();
            Environment.Exit(1);
            return;
        }
    }
}
